package uncompress

import (
	"encoding/json"
	"log"
	"sync"

	"github.com/mholt/archiver"
	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/store"
	"smartconn.cc/tosone/ra_main/taskMgr"
)

const serviceName = "uncompress"

var err error

func init() {
	var locker sync.Mutex
	var channel chan common.ServiceCommand

	taskMgr.Register(serviceName, channel)
	go func() {
		for {
			select {
			case control := <-channel:
				switch control.Cmd {
				case "start":
					locker.Lock()
					uncompress()
					locker.Unlock()
				}
			}
		}
	}()
}

func uncompress() {
	id, taskContent, err := store.GetATask(serviceName)
	if err != nil {
		log.Println(err)
		return
	}

	var content common.TaskContentUncompress
	err = json.Unmarshal([]byte(taskContent), &content)
	if err != nil {
		log.Println(err)
		return
	}

	err = archiver.TarGz.Open(content.File, content.Path)
	if err != nil {
		log.Println(err)
		return
	}

	syncTaskContent, err := json.Marshal(common.TaskContentSync{Path: content.Path})
	if err != nil {
		log.Println(err)
		return
	}
	store.AddTask("syncStory", string(syncTaskContent))

	store.RemoveTask(id)
}
